package ru.housewife.service.daymenus;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.DayMenuForm;
import ru.housewife.form.UsersTableForm;
import ru.housewife.model.DayMenu;
import ru.housewife.model.UsersTable;

/**
 * saves new day menu
 *
 * @author Alexander Troshanin
 */
public class AddNewDayMenu implements HibernateAction<DayMenu> {

    private DayMenuForm dayMenuForm;

    public AddNewDayMenu(DayMenuForm dayMenuForm) {
        this.dayMenuForm = dayMenuForm;
    }

    @Override
    public DayMenu execute(Session session) {
        UsersTableForm usersTableForm = dayMenuForm.getUsersTable();
        UsersTable usersTable = (UsersTable) session.get(UsersTable.class, usersTableForm.getId());
        if (usersTable == null) {
            return null;
        }

        DayMenu dayMenu = new DayMenu();
        dayMenu.setDayNumber(dayMenuForm.getDayNumber());
        dayMenu.setUsersTable(usersTable);

        session.save(dayMenu);
        dayMenuForm.setId(dayMenu.getId());
        usersTableForm.addDayMenu(new DayMenuForm(usersTableForm, dayMenu));

        // todo: check whether it is necessary to add: usersTable.getDayMenus().add(dayMenu); session.save(usersTable);

        return dayMenu;
    }
}
